#!/usr/bin/env python
# -*- coding: utf-8 -*-
# by vellhe 2020/12/01
from flask import Flask, abort, request, jsonify
import base64
import io
import qrcode

app = Flask(__name__)

@app.route('/build-qr', methods=['POST'])
def add_task():
    if not request.json or 'data' not in request.json:
        abort(400)
    data = request.json['data']
    bcode = base64.b64encode(data.encode('utf-8'))
    print(bcode)
    qr = qrcode.QRCode(     
        version=1,     
        error_correction=qrcode.constants.ERROR_CORRECT_L,     
        box_size=10,     
        border=1, 
    )
    qr.make(fit=True) 
    qr.add_data(bcode)
    img = qr.make_image()
    buf = io.BytesIO()
    img.save(buf,format='PNG')
    image_stream = buf.getvalue()
    heximage = base64.b64encode(image_stream)
    result = 'data:image/png;base64,' + heximage.decode()
    return jsonify({'result': result})


@app.route('/hello', methods=['GET'])
def get_task():
    return "hello flash"


if __name__ == "__main__":
    # 将host设置为0.0.0.0，则外网用户也可以访问到这个服务
    app.run(host="0.0.0.0", port=7004, debug=True)
